<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

class OrdersTrash extends Backend
{
    public function __construct()
    {
        parent::__construct();
        $this->lang->load('sites');
        $this->load->model(['site_model','sitecategory_model','siteproduct_model','siteuser_model','siteorder_model','sf_model']);
        $this->data['page_home']  = lang('lang_dashboard');
        $this->data['page_title'] = lang('lang_orders_trash_can');
    }

    public function index()
    {
        // Title
        $this->data['meta_title'] = $this->data['page_title'];

        // Breadcrumbs
        $this->data['array_breadcrumbs'] = array(
            $this->data['page_home']  => 'backend',
            '询盘垃圾箱'=>'backend/OrdersTrash'
        );

        $this->data['content_header_title'] = content_header_title($this->data['page_title'],'垃圾箱');
        $this->data['content'] = 'orderstrash';
        $this->data['sitetype'] = $this->config->item('site_types');
        $this->data['sindex']=$this->site_model->get_name_index();
        $key=trim($this->input->get('keyword'));

        $config = $this->systemconfig_model->get_configs();
        $this->data['config']=$config;

        $key=trim($this->input->get('keyword'));
        if(substr($key, -1)==">")
        {
            $key=substr($key,0,-1);
        }

        $page=max(1,(int) $this->input->get('page'));
        $sitetype=intval($this->input->get('sitetype'));
        $shopfrom=trim($this->input->get('shopfromm'));
        $pagesize=intval($this->input->get('pagesize'));
        $timelimit=$this->input->get("timelimit");

        if($pagesize){
            set_cookie("pagesize",$pagesize,60*60*24);
        }else{
            $pagesize=get_cookie("pagesize");
        }
        $this->data['sindex']=$this->site_model->get_name_index();

        $siteid=[];
        if($key)
        {
            foreach($this->data['sindex'] as $k=>$v)
            {
                if(strstr(strtolower($v),strtolower($key)))
                {
                    $siteid[]=$k;
                }
            }
            if(count($siteid)>0)
            {
                $key="";
            }
        }
        if($sitetype>0)
        {
            $sites=$this->site_model->getsitetype($sitetype);
            if($sites)
            {
                $siteid=[];
                foreach($sites as $s)
                {
                    $siteid[]=$s["id"];
                }
            }
        }
        $spsite=[];
        $spsites=[];
        $shopifysite=$this->site_model->getallsync();
        if($shopifysite):
            foreach($shopifysite as $ac)
            {
                $spsite[]=$ac["id"];
                $spsites[$ac["id"]]=$ac;
            }
        endif;
        $this->data['spsite']=$spsite;
        $this->data['spsites']=$spsites;

        $state= '-1';
        $siteid=(int) $this->input->get('state');
        $except=(int) $this->input->get('except');

        $export=intval($this->input->get('export'));
        if($export==1)
        {
            $orders=$this->siteorder_model->getbyfilter($siteid,$key,0,$state,$timelimit,$except,$shopfrom);
            $this->makexlsx($orders);
        }
        $page_data=$this->siteorder_model->getpage($siteid,$page,$pagesize,$key,0,$state,$timelimit,$except,$shopfrom);
        $this->data['loglist']=$page_data["data"];
        $this->data['pager']=$page_data["pager"];
        $this->data['total']=$page_data["total"];
        $this->data['pages']=$page_data["pages"];
        $this->data['page']=$page;
        $this->data['sitetype'] = $this->config->item('site_types');
        $this->data['state']=$state;
        $keyword = array(
            'name'      => 'keyword',
            'id'        => 'keyword',
            'value'     =>  $key,
            'class'     =>  'form-control input-sm',
            'placeholder'=> '快速查询关键字',
            'maxlength' => '100'
        );
        $this->data['keyword']=$keyword;
        $page_data=$this->siteorder_model->getpage($siteid,$page,$pagesize,$key,0,$state,$timelimit,$except,$shopfrom);
        $this->data['loglist']=$page_data["data"];
        $this->render();
    }

    public function ordersajaxrep()
    {
        $return=["status"=>1];
        $id=$this->input->post("cid");
        $newdata['state'] = '0';
        $this->siteorder_model->update($id,$newdata);
        echo json_encode($return);
        die();
    }

    private function makexlsx($data)
    {


        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet()->setTitle(date("Y-m-d").'询盘列表');

        $field=["站点id","真实姓名","邮箱","电话","数量","留言","时间","ip地址","来源"];
        $i=0;
        foreach ($field as $key => $value) {
            $sheet->getColumnDimension(num2alpha($i))->setAutoSize(true);
            $sheet->setCellValue(num2alpha($i).'1', $value);
            $i++;
        }
        $rowcount=1;
        if($data):
            foreach($data as $k=>$item)
            {
                $rowcount++;
                $v=[$item["siteid"],$item["realname"],$item["email"],$item["phone"],$item["quantity"],$item["info"],date("Y-m-d",strtotime($item["addtime"])),$item["ipaddr"],$item["url"]];
                $i=0;
                foreach($field as $key=>$value){
                    $sheet->getCell(num2alpha($i++).$rowcount)->setValueExplicit(
                        $v[$key],
                        \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING
                    );
                }

            }
        endif;

        $writer = new Xlsx($spreadsheet);
        $filename=date("Y-m-d.H/i/s")."垃圾箱.xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
        die();
    }
}